<template>
  <div id="cesiumContainer" ref="cesiumContainer" style="width: 100%;height: 100vh;"></div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import * as Cesium from 'cesium';
// 引入pinia
import {storeVuex} from  '@/store/modules/user'
const Vuex = storeVuex()
import ShopIcon from '@/assets/icon/xyIcon.png'
import clientIcon from '@/assets/icon/tbzz_xhq.png'
// 设置Cesium的基础URL（如果你将Cesium的assets文件复制到了public目录）
// if (typeof window !== 'undefined') {
//   window.CESIUM_BASE_URL = '/';
// }
const Map = ref(null)
onMounted(() => {
  init()
});
let viewer;
const init = ()=>{
  const token = "c40011ae1e40d5d7bce2a1690143a111"
  // const token = "497888eb757ed21b4e215135597830cc"
  const tdtUrl = 'https://t{s}.tianditu.gov.cn/'
  const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']
  Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwOTAwZTc0MS0wMWMxLTQ5ZmUtYWNkZi01ZTRjYzEwMjYxNTYiLCJpZCI6NjcwMzMsImlhdCI6MTYzMTUwMzM1Mn0.BGqWSH9wfUZaH6Svb5hKz3UBFdv3WbFiAP02CzORzso'
  // 创建
  viewer = new Cesium.Viewer("cesiumContainer", {
    imageryProvider:false,
    // terrainProvider: terrainProvider,
    homeButton: false, // 是否显示主页按钮
    scene3DOnly : true,
    animation: false, // 是否显示左下角的仪表盘
    navigationHelpButton: false, // 是否显示右上角的帮助按钮
    infoBox: false, // 是否显示提示信息
    selectionIndicator: false,
    baseLayerPicker: false,
    geocoder: false,
    timeline: false,
    fullscreenButton: false,
    shouldAnimate: false,
    url:'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
  });
  //西南东北，默认显示中国
  Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees( 113.307, 33.733, 90)
  // 地球皮肤
  viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
        url: tdtUrl + 'DataServer?T=img_w&x={x}&y={y}&l={z}&tk=' + token,
        subdomains: subdomains,
        tilingScheme : new Cesium.WebMercatorTilingScheme(),
        maximumLevel : 18
      }));
  // 加载省市区
  viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
    url: "http://t0.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=c40011ae1e40d5d7bce2a1690143a111",
    layer: "tdtAnnoLayer",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "GoogleMapsCompatible",
    show: false
  }));
  // 叠加天地图影像国境线服务
  viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
    url: tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + token,
    subdomains: subdomains,
    tilingScheme : new Cesium.WebMercatorTilingScheme(),
    maximumLevel : 18
  }));
  viewer._cesiumWidget._creditContainer.style.display = "none";
  // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 10000; // 设置最大高度为 5000 米
  window.viewer = viewer;


  addCanner() //添加武汉城市白模场景
  getMapXY()  //鼠标点击获取当前坐标
  drawWater(riversList) //创建水面
  load3dTiles() //添加东方绿洲倾斜摄影模型
}
// 添加东方绿洲倾斜摄影模型
const load3dTiles = async (e)=>{
 try {
   const tileset = await Cesium.Cesium3DTileset.fromUrl('/models/dflz_new/tileset.json', {
   enableDraco: true,            //
   shadows: true,                 // 启用阴影
   preferLeaves: true,            // 优先加载叶节点
   maximumScreenSpaceError: 1,   // 屏幕空间误差(值越小越精细，性能消耗越大)
   maximumMemoryUsage: 2048    ,   // 最大内存使用(MB)
   skipLevelOfDetail: false,      // 禁用跳级加载以避免Draco解码问题
   preloadWhenHidden: true,       // 预加载隐藏的瓦片
   preloadFlightDestinations: true, // 预加载飞行目的地
   dynamicScreenSpaceError: true  // 动态屏幕空间误差
 });
   // 添加到场景
   viewer.scene.primitives.add(tileset);

   // 设置模型的高度
   const heightOffset = 6; // 设置一个合适的高度偏移（单位：米）
   tileset.modelMatrix = Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(0, 0, heightOffset));

   // 视图定位到模型
   viewer.zoomTo(tileset);
 } catch (error) {
   console.log('加载模型错误',error);
 }
}

// 添加汽车模型
const addModel_car = (e)=>{
  let model = e.entities.add({
    position:Cesium.Cartesian3.fromDegrees(121.0301409,30.6806447,-0.9),
    model:{
      show:true,
      uri:'/glb/bccar.glb',
      scale:1
    }
  })
  e.flyTo(model)
}

// 在全局或类作用域中定义数组
let shopEntities = []; //店铺位置
let userEntities = []; //饭店客户位置
let lineEntities = []; //配送路线位置

// 添加南宁市白膜数据并应用特效
const addCanner = async () => {
    //  Cesium.ExperimentalFeatures.enableModelExperimental = true
    debugger
    var height = -1.1406325468715177e-9;
    var heading = 0;
    const tileset = await  Cesium.Cesium3DTileset.fromUrl(
        '/models/nanning/tileset.json', //测试数据上海东方明珠建筑数据
    );
    viewer.scene.primitives.add(tileset,{
      disableDepthTestDistance: Number.POSITIVE_INFINITY
    });
    tileset.style = new Cesium.Cesium3DTileStyle({
      color: {
        conditions: [["true", "color('rgb(51, 153, 255)',1)"]],
      },
    });
    var customShader = new Cesium.CustomShader({
      //不考虑光照模型
      lightingModel: Cesium.LightingModel.UNLIT,
      //修改片元着色器
      fragmentShaderText: `
                void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
                            float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
                            float _heightRange = 60.0; // 高亮的范围(_baseHeight ~ _baseHeight + _      heightRange) 默认是 0-60米
                            float _glowRange = 300.0; // 光环的移动范围(高度)
                        float vtxf_height = fsInput.attributes.positionMC.z-_baseHeight;
                        float vtxf_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
                        float vtxf_a12 = vtxf_height / _heightRange + sin(vtxf_a11) * 0.1;
                        material.diffuse*= vec3(vtxf_a12, vtxf_a12, vtxf_a12);
                        float vtxf_a13 = fract(czm_frameNumber / 360.0);
                        float vtxf_h = clamp(vtxf_height / _glowRange, 0.0, 1.0);
                        vtxf_a13 = abs(vtxf_a13 - 0.5) * 2.0;
                        float vtxf_diff = step(0.005, abs(vtxf_h - vtxf_a13));
                        material.diffuse += material.diffuse * (1.0 - vtxf_diff);
                    }
                    `,
    });
    tileset.customShader = customShader;
    viewer.zoomTo(tileset)
}

//声明移动的电车实例
let animateEntity;
const dpcCar = (positions, speed = 25) => {
  // 新增一个高度偏移参数，默认为 0.5 米
  let heightOffset = 0.5
  const start = new Date(2001, 0, 5, 16);
  const julianStart = Cesium.JulianDate.fromDate(start);

  const position = new Cesium.SampledPositionProperty();
  let currentJulianTime = julianStart; // 初始化时间

  // 为每个位置添加样本
  for (let i = 0; i < positions.length - 1; i++) {
    const [lon1, lat1] = positions[i];
    const [lon2, lat2] = positions[i + 1];

    // 添加高度偏移
    const startCartesian = Cesium.Cartesian3.fromDegrees(lon1, lat1, heightOffset);
    const endCartesian = Cesium.Cartesian3.fromDegrees(lon2, lat2, heightOffset);

    // 计算点与点之间的距离
    const distance = Cesium.Cartesian3.distance(startCartesian, endCartesian);

    // 计算到达下一个点的时间（秒）
    const timeToNextPoint = distance / speed; // 使用设定的速度

    // 将当前位置添加到已采样的位置
    position.addSample(currentJulianTime, startCartesian);

    // 更新当前时间
    currentJulianTime = Cesium.JulianDate.addSeconds(currentJulianTime, timeToNextPoint, new Cesium.JulianDate());

    // 添加目标位置
    position.addSample(currentJulianTime, endCartesian);
  }

  // 计算总的停止时间
  const julianStop = Cesium.JulianDate.addSeconds(currentJulianTime, 0, new Cesium.JulianDate());

  // 设置时钟
  viewer.clock.startTime = julianStart;
  viewer.clock.stopTime = julianStop;
  viewer.clock.currentTime = julianStart;
  viewer.clock.shouldAnimate = true;

  // 添加实体到视图
  animateEntity = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: julianStart,
        stop: julianStop
      }),
    ]),
    position: position,
    orientation: new Cesium.VelocityOrientationProperty(position),
    model: {
      scale: 0.2,
      uri: "/models/dianche/scene.glb", // 确保路径正确
      minimumPixelSize: 0
    }
  });

  // viewer.trackedEntity = carEntity; // 追踪该实体
};
//声明移动的汽车实例
let carEntity;
const bcCar = (positions, speed = 15) => {
  // 新增一个高度偏移参数，默认为 0.5 米
  let heightOffset = 1
  const start = new Date(2001, 0, 5, 16);
  const julianStart = Cesium.JulianDate.fromDate(start);

  const position = new Cesium.SampledPositionProperty();
  let currentJulianTime = julianStart; // 初始化时间

  // 为每个位置添加样本
  for (let i = 0; i < positions.length - 1; i++) {
    const [lon1, lat1] = positions[i];
    const [lon2, lat2] = positions[i + 1];

    // 添加高度偏移
    const startCartesian = Cesium.Cartesian3.fromDegrees(lon1, lat1, heightOffset);
    const endCartesian = Cesium.Cartesian3.fromDegrees(lon2, lat2, heightOffset);

    // 计算点与点之间的距离
    const distance = Cesium.Cartesian3.distance(startCartesian, endCartesian);

    // 计算到达下一个点的时间（秒）
    const timeToNextPoint = distance / speed; // 使用设定的速度

    // 将当前位置添加到已采样的位置
    position.addSample(currentJulianTime, startCartesian);

    // 更新当前时间
    currentJulianTime = Cesium.JulianDate.addSeconds(currentJulianTime, timeToNextPoint, new Cesium.JulianDate());

    // 添加目标位置
    position.addSample(currentJulianTime, endCartesian);
  }

  // 计算总的停止时间
  const julianStop = Cesium.JulianDate.addSeconds(currentJulianTime, 0, new Cesium.JulianDate());

  // 设置时钟
  viewer.clock.startTime = julianStart;
  viewer.clock.stopTime = julianStop;
  viewer.clock.currentTime = julianStart;
  viewer.clock.shouldAnimate = true;

  // 添加实体到视图
  carEntity = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: julianStart,
        stop: julianStop
      }),
    ]),
    position: position,
    orientation: new Cesium.VelocityOrientationProperty(position),
    model: {
      scale: 1,
      uri: "/models/dianche/bsj.glb", // 确保路径正确
      minimumPixelSize: 0
    }
  });

  // viewer.trackedEntity = carEntity; // 追踪该实体
};
//声明移动的飞机实例
let planeEntity;
const planeCar = (positions, speed = 1500) => {
  // 新增一个高度偏移参数，默认为 0.5 米
  let heightOffset = 10000
  const start = new Date(2001, 0, 5, 16);
  const julianStart = Cesium.JulianDate.fromDate(start);

  const position = new Cesium.SampledPositionProperty();
  let currentJulianTime = julianStart; // 初始化时间

  // 为每个位置添加样本
  for (let i = 0; i < positions.length - 1; i++) {
    const [lon1, lat1] = positions[i];
    const [lon2, lat2] = positions[i + 1];

    // 添加高度偏移
    const startCartesian = Cesium.Cartesian3.fromDegrees(lon1, lat1, heightOffset);
    const endCartesian = Cesium.Cartesian3.fromDegrees(lon2, lat2, heightOffset);

    // 计算点与点之间的距离
    const distance = Cesium.Cartesian3.distance(startCartesian, endCartesian);

    // 计算到达下一个点的时间（秒）
    const timeToNextPoint = distance / speed; // 使用设定的速度

    // 将当前位置添加到已采样的位置
    position.addSample(currentJulianTime, startCartesian);

    // 更新当前时间
    currentJulianTime = Cesium.JulianDate.addSeconds(currentJulianTime, timeToNextPoint, new Cesium.JulianDate());

    // 添加目标位置
    position.addSample(currentJulianTime, endCartesian);
  }

  // 计算总的停止时间
  const julianStop = Cesium.JulianDate.addSeconds(currentJulianTime, 0, new Cesium.JulianDate());

  // 设置时钟
  viewer.clock.startTime = julianStart;
  viewer.clock.stopTime = julianStop;
  viewer.clock.currentTime = julianStart;
  viewer.clock.shouldAnimate = true;

  // 添加实体到视图
  planeEntity = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: julianStart,
        stop: julianStop
      }),
    ]),
    position: position,
    orientation: new Cesium.VelocityOrientationProperty(position),
    model: {
      scale: 1,
      uri: "/models/dianche/feiji.glb", // 确保路径正确
      minimumPixelSize: 0
    }
  });
  // viewer.trackedEntity = planeEntity; // 追踪该实体
};
//声明攻击日本的军舰
let boatEntity;
const boatCar = (positions, speed = 150) => {
  // 新增一个高度偏移参数，默认为 0.5 米
  let heightOffset = 1000
  const start = new Date(2001, 0, 5, 16);
  const julianStart = Cesium.JulianDate.fromDate(start);

  const position = new Cesium.SampledPositionProperty();
  let currentJulianTime = julianStart; // 初始化时间

  // 为每个位置添加样本
  for (let i = 0; i < positions.length - 1; i++) {
    const [lon1, lat1] = positions[i];
    const [lon2, lat2] = positions[i + 1];

    // 添加高度偏移
    const startCartesian = Cesium.Cartesian3.fromDegrees(lon1, lat1, heightOffset);
    const endCartesian = Cesium.Cartesian3.fromDegrees(lon2, lat2, heightOffset);

    // 计算点与点之间的距离
    const distance = Cesium.Cartesian3.distance(startCartesian, endCartesian);

    // 计算到达下一个点的时间（秒）
    const timeToNextPoint = distance / speed; // 使用设定的速度

    // 将当前位置添加到已采样的位置
    position.addSample(currentJulianTime, startCartesian);

    // 更新当前时间
    currentJulianTime = Cesium.JulianDate.addSeconds(currentJulianTime, timeToNextPoint, new Cesium.JulianDate());

    // 添加目标位置
    position.addSample(currentJulianTime, endCartesian);
  }

  // 计算总的停止时间
  const julianStop = Cesium.JulianDate.addSeconds(currentJulianTime, 0, new Cesium.JulianDate());

  // 设置时钟
  viewer.clock.startTime = julianStart;
  viewer.clock.stopTime = julianStop;
  viewer.clock.currentTime = julianStart;
  viewer.clock.shouldAnimate = true;

  // 添加实体到视图
  boatEntity = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: julianStart,
        stop: julianStop
      }),
    ]),
    position: position,
    orientation: new Cesium.VelocityOrientationProperty(position),
    model: {
      scale: 10,
      uri: "/models/dianche/junjian.glb", // 确保路径正确
      minimumPixelSize: 0
    }
  });
  // viewer.trackedEntity = planeEntity; // 追踪该实体
};


// 删除追踪实例
const delEntity = () =>{
  viewer.entities.remove(animateEntity);
  viewer.entities.remove(carEntity);
  viewer.entities.remove(planeEntity);
  viewer.entities.remove(boatEntity);
}
// 点击定位
const addGps = (e,t,icon) => {
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(114.31652350524024, 30.357989020221492, 10000), // 高度可以设置得更高
    duration: 2
  });
  // 添加标记和事件
  e.forEach(location => {
    const position = Cesium.Cartesian3.fromDegrees(
        location.coordinates.longitude,
        location.coordinates.latitude,
        50 // 可以调整高度
    );
    // 添加点
    let entity = viewer.entities.add({
      position: position,
      name: location.name,
      billboard: {
        image: icon,
        width: 30, // 图标宽度
        height: 30, // 图标高度
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      },
      label: {
        text: location.name,
        font: "18px Helvetica",
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.TOP,
        pixelOffset: new Cesium.Cartesian2(0, 10)
      }
    });
    if (t){
      shopEntities.push(entity); // 保存实体引用
    }else{
      userEntities.push(entity); // 保存实体引用
    }
  });
  // 设置点击事件
  viewer.screenSpaceEventHandler.setInputAction((click) => {
        const pickedObject = viewer.scene.pick(click.position);
        if (Cesium.defined(pickedObject)) {
          // 在某些情况下使用 id, 在另一些情况下使用 entity
          const entity = pickedObject.id || pickedObject.entity;
          if (entity) {
            // 获取实体的当前位置
            let position = entity.position.getValue(Cesium.JulianDate.now());
            // 从 position 中提取经纬度单独设置跳转的视角
            const cartographic = Cesium.Cartographic.fromCartesian(position);
            const longitude = Cesium.Math.toDegrees(cartographic.longitude);
            const latitude = Cesium.Math.toDegrees(cartographic.latitude);
            viewer.camera.flyTo({
              destination:Cesium.Cartesian3.fromDegrees(longitude, latitude, 300),
              duration: 2, // 设置动画过渡时长
              orientation: {
                heading: Cesium.Math.toRadians(0.0), // 可以调整朝向
                pitch: Cesium.Math.toRadians(-90), // 俯视角度
                roll: 0.0
              }
            });
            // 删除移动的实体
            delEntity()
          }
        }
      },
  Cesium.ScreenSpaceEventType.LEFT_CLICK);
 }
// 点击东方绿洲定位
const adddflzGps = (e,t,icon) => {
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(121.03207560834326,30.682607079273, 500), // 高度可以设置得更高
    duration: 3
  });
  // 添加标记和事件
  e.forEach(location => {
    const position = Cesium.Cartesian3.fromDegrees(
        location.coordinates.longitude,
        location.coordinates.latitude,
        14 // 可以调整高度
    );
    // 添加点
    let entity = viewer.entities.add({
      position: position,
      name: location.name,
      billboard: {
        image: icon,
        width: 30, // 图标宽度
        height: 30, // 图标高度
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      },
      label: {
        text: location.name,
        font: "18px Helvetica",
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.TOP,
        pixelOffset: new Cesium.Cartesian2(0, 10)
      }
    });
    if (t){
      shopEntities.push(entity); // 保存实体引用
    }else{
      userEntities.push(entity); // 保存实体引用
    }
  });
  // 设置点击事件
  viewer.screenSpaceEventHandler.setInputAction((click) => {
        const pickedObject = viewer.scene.pick(click.position);
        if (Cesium.defined(pickedObject)) {
          // 在某些情况下使用 id, 在另一些情况下使用 entity
          const entity = pickedObject.id || pickedObject.entity;
          if (entity) {
            // 获取实体的当前位置
            let position = entity.position.getValue(Cesium.JulianDate.now());
            // 从 position 中提取经纬度单独设置跳转的视角
            const cartographic = Cesium.Cartographic.fromCartesian(position);
            const longitude = Cesium.Math.toDegrees(cartographic.longitude);
            const latitude = Cesium.Math.toDegrees(cartographic.latitude);
            viewer.camera.flyTo({
              destination:Cesium.Cartesian3.fromDegrees(longitude, latitude, 50),
              duration: 2, // 设置动画过渡时长
              orientation: {
                heading: Cesium.Math.toRadians(0), // 可以调整朝向
                pitch: Cesium.Math.toRadians(-80), // 俯视角度
                roll: 0
              }
            });
            // 删除移动的摩托实体
            delEntity()
          }
        }
      },
  Cesium.ScreenSpaceEventType.LEFT_CLICK);
 }
// 移动初始视角
const createCamera = (e)=>{
  switch (e) {
    case "南宁":
      viewer.camera.flyTo({
        // 114.3197037856055, 30.370231035919726,
        destination: Cesium.Cartesian3.fromDegrees(
            108.29246484715276,22.812929009792175
            ,200),
        duration: 2, // 飞行时间
        orientation: {
          heading: Cesium.Math.toRadians(0.0), // 面朝北
          pitch: Cesium.Math.toRadians(-20), // 向下俯视
          roll: 0.0
        }
      });
      break;
  }
}
//获取点击的坐标
const getMapXY = ()=>{
  // 设置点击事件获取坐标
  viewer.screenSpaceEventHandler.setInputAction((click) => {
    // 获取屏幕空间坐标
    const pickedPosition = viewer.scene.pickPosition(click.position);
    // 检查是否选择到了有效的位置
    if (Cesium.defined(pickedPosition)) {
      const cartographic = Cesium.Cartographic.fromCartesian(pickedPosition);

      // 获取经纬度
      const longitude = Cesium.Math.toDegrees(cartographic.longitude);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude);
      const height = cartographic.height; // 可以添加高度信息

      // 打印坐标到控制台
      console.log(`${longitude},${latitude}`);
    } else {
      console.log("未选择到有效的位置");
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

//添加
const addLine = (title) => {
  switch (title) {
    case '店铺':
      addGps(Vuex.GpsShopList.shop,true,ShopIcon)
      break;
    case '客户':
      addGps(Vuex.GpsShopList.customer,false,clientIcon)
      break;
    case '快递驿站':
      adddflzGps(Vuex.GpsShopList.dflz,false,clientIcon)
      break;
    case '超市':
      adddflzGps(Vuex.GpsShopList.dflz,false,clientIcon)
      break;
    case '家':
      adddflzGps(Vuex.GpsShopList.dflz,false,clientIcon)
      break;
    case '配送路线':
      // 添加所有线条
      Vuex.GpsShopList.line.forEach(line => {
        addTrailLine(line);
      });
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(114.3197037856055, 30.370231035919726, 10000), // 确保高于多边形
        duration: 2 // 2秒动画
      });
      break;
    case '进货位置':
      addMian(Vuex.GpsShopList.addShopGps,title)
      break;
    case '货源位置':
      addMian(Vuex.GpsShopList.homeShopGps,title)
      break;
  }
}
//添加线
const addTrailLine = (e) => {
  let start = e[0]
  let end = e[1]
  // 创建线的位置
  const trailPositions = [
    Cesium.Cartesian3.fromDegrees(start[0], start[1]),
    Cesium.Cartesian3.fromDegrees(end[0], end[1])
  ];
  // 添加线到地图上
  const line = viewer.entities.add({
    name: 'Trail Line',
    polyline: {
      positions: trailPositions,
      width: 5, // 线的宽度
      // material: Cesium.Color.RED.withAlpha(0.7) // 线的颜色和透明度
      material: new Cesium.PolylineGlowMaterialProperty({
        color:Cesium.Color.RED,
        glowPower:0.12
      })
    },
  });
  lineEntities.push(line);
}
//删除线
const delLine = ()=>{
  lineEntities.forEach(entity => {
    viewer.entities.remove(entity);
  });
  lineEntities = []; // 清空数组
}
//删除
const remove = (title)=>{
  switch (title) {
    case '店铺':
      delGps(true)
      break;
    case '客户':
      delGps(false)
      break;
    case '配送路线':
      delLine()
      break;
    case '进货位置':
      delViewer(title)
      break;
    case '货源位置':
      delViewer(title)
      break;
  }
  // viewer.entities.removeAll();
}
//删除点位
const delGps = (e)=>{
  if (e){
    shopEntities.forEach(entity => {
      viewer.entities.remove(entity);
    });
    shopEntities = []; // 清空数组
  }else{
    userEntities.forEach(entity => {
      viewer.entities.remove(entity);
    });
    userEntities = []; // 清空数组
  }

}
// 删除面
const delViewer = (id)=>{
  const entity = viewer.entities.getById(id);
  if (entity) {
    viewer.entities.remove(entity);
    console.log('矩形已删除');
  } else {
    console.log('未找到要删除的矩形');
  }
}
// 创建矩形
const addMian = (e,title)=>{
  const entity = viewer.entities.add({
    id: title,
    name: "面",
    show: true,
    polygon: {
      hierarchy: Cesium.Cartesian3.fromDegreesArray(e), //参数为四个角点坐标
      material: Cesium.Color.BLUE.withAlpha(0.5)
    }
  })
// 计算多边形的中心位置
  const centerLon = (e[0] + e[2]) / 2; // 经度
  const centerLat = (e[1] + e[3]) / 2; // 纬度
  let gps = []
  switch (title){
    case '进货位置':
      gps = [114.20610405021715,30.597762291956723]
      break;
    case '货源位置':
      gps = [113.34126931360181,33.59724028882954]
      break;
  }
// 在中心点添加文字标注，设置高度
  viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(gps[0],gps[1],1),
    label: {
      text: title, // 使用传入的title作为文本
      font: '20px Helvetica',
      fillColor: Cesium.Color.WHITE, // 字体颜色
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 2,
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 底部对齐
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER // 水平中央对齐
    }
  });
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, 600), // 确保高于多边形
    duration: 2 // 2秒动画
  });
}

//开始配送
const giveShop = (e) =>{
  dpcCar([
        [114.31685762885856,30.357774924530627],
        [114.3165468368824,30.357013041591905],
        [114.31431455704664,30.35679097916735],
        [114.31197810216213,30.370332583764423],


        [114.3329260342836,30.370354158026284],
        [114.33382864082581,30.37018306361339],
        [114.3357979126859,30.37069280674231],
        [114.34664458796348,30.37234266262515],
        [114.34874853233707,30.372656151454994],
        [114.34980176884137,30.372875139986505],
        [114.35113075765511,30.373290782424874],
        [114.35229089191103,30.37381117415371],
        [114.35377574657973,30.375038879203984],
        [114.35556613572203,30.375482433035035],
        [114.36066150890737,30.377898434041114],
        [114.36228129089487,30.37840476966906],
        [114.36433206287042,30.37871215415335],
        [114.3664101183443,30.378645246561025],
        [114.36651446886867,30.38222159277543],
        [114.36608985542863,30.382197455569838],
        [114.36547033919791,30.381153390821225],
        [114.36448190285908,30.381449104594314],
        [114.36402249198842,30.380936115182813]
      ])
  delEntity()
}

const mapLant = reactive([
  [121.03508038407914,30.682459572529655],
  [121.03334882609805,30.68181367110628],
  [121.03120256518174,30.681046674123387],
  [121.03094922306101,30.680986870723324],
  [121.03025972778998,30.680742370243035],
  [121.03018320416231,30.6807714492358],
  [121.03012128303237,30.68081538954362],
  [121.03006581702171,30.680879446296142],
  [121.02987738403758,30.68150985288589],
  [121.02970598553281,30.68220924433003],
  [121.02936890053752,30.684290879740253],
  [121.02940158081677,30.684404665928728],
  [121.02943101064274,30.684459340251426],
  [121.02952768318227,30.68456072757396],
  [121.02967977427963,30.68463035384133],
  [121.02984009420554,30.684684597461793],
  [121.03065517970309,30.684899208185644]
])
const feijiLant = reactive([
    [121.333290960879,31.18339635385414],
    [121.33269586717282,31.19418327611154],
    [121.33171977390924,31.212828082595422],
    [121.32918909518523,31.24316798884466],
    [121.32323824031405,31.26924924931721],
    [121.30134393243485,31.298583682808992],
    [121.14129726840048,31.444984370911627],
    [120.88197135860254,31.48546773043575],
    [120.57738821150363,31.488769206350515],
    [120.22960139450687,31.405063702660303],
    [108.1925434776002,22.630447283755732],
    [108.18693843073126,22.618442170864625],
    [108.17606887609432,22.609118929144742]
  ])
//开始行驶
const giveCar = (e) =>{
  bcCar(mapLant)
  dpcCar(mapLant)
  planeCar(feijiLant)
  boatCar([
      [122.7844411548107,30.956712605040703],
      [141.97342789193027,32.96465444302685],
      [143.23802108665473,37.42071416648962]
  ])
}
// 监听实体
const lookCar = (e) =>{
  switch (e) {
    case "animateEntity":
      viewer.trackedEntity = animateEntity; // 追踪该实体
      break;
    case "carEntity":
      viewer.trackedEntity = carEntity; // 追踪该实体
      break;
    case "planeEntity":
      viewer.trackedEntity = planeEntity; // 追踪该实体
      break;
    case "boatEntity":
      viewer.trackedEntity = boatEntity; // 追踪该实体
      break;
  }
}
// 水面数据
const riversList = [
  121.03040405166824,30.680289408829605,
  121.03182652063934,30.680802722595004,
  121.03308168157032,30.68141459952884,
  121.03359069191939,30.68169204930067,
  121.03492077257339,30.682260000074404,
  121.0353070912433,30.682429075033074,
  121.03559076522626,30.68195487378902,
  121.03455498959177,30.681584429293412,
  121.0345684119317,30.680675501665135,
  121.033979067333,30.680579662883904,
  121.03370660036367,30.681319895134138,
  121.0321732322774,30.68069895344634,
  121.0305350701163,30.679997525644204,
  121.0304186066004,30.68026693938491
]
// 创建水面效果
const drawWater = (data) => {
  viewer.scene.primitives.add(
      new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
          geometry: new Cesium.PolygonGeometry({
            // 定义水面多边形区域
            polygonHierarchy: new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArray(data)
            ),
            vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
          }),
        }),
        appearance: new Cesium.EllipsoidSurfaceAppearance({
          aboveGround: true,
          material: new Cesium.Material({
            fabric: {
              type: 'Water', // 使用内置水面材质
              uniforms: {
                // 水面材质参数配置
                normalMap: Cesium.buildModuleUrl('/img/sm.png'),
                frequency: 1000.0, // 波浪频率
                animationSpeed: 0.01, // 波浪动画速度
                amplitude: 10, // 波浪振幅
              },
            },
          }),
        }),
        show: true,
      })
  );
}
// 查看智慧城市
const lookCity = () => {
  createCamera('南宁')
  // 删除移动的实体
  delEntity()
}
// 将方法暴露给父组件
defineExpose({
  addLine,remove,giveShop,giveCar,lookCar,lookCity,delEntity
});
</script>
<style scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>
